package edu.cuit.avatar.concurrent;

/**
 * @author <a href="mailto:1020zhaodan@163.com">Adan</a>
 * @version 1.0
 * @date 2025/7/17 10:30
 */
public class DeadLockDemo {
    private static final Object lock1 = new Object();
    private static final Object lock2 = new Object();

    public static void main(String[] args) {
        Thread t1 = new Thread(() ->{
            synchronized (lock1){
                System.out.println(Thread.currentThread().getName() + ": holding lock 1...");
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println(Thread.currentThread().getName() + ": waiting for lock 2...");
                synchronized (lock1){
                    System.out.println(Thread.currentThread().getName() + ": lock 2...");
                }
            }
        });
        t1.start();
        Thread t2 = new Thread(() ->{
            synchronized (lock2){
                System.out.println(Thread.currentThread().getName() + ": holding lock 2...");
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println(Thread.currentThread().getName() + ": waiting for lock 1...");
                synchronized (lock2){
                    System.out.println(Thread.currentThread().getName() + ": lock 1...");
                }
            }
        });
        t2.start();
    }
}
